import random

from django.http import HttpResponse
from redis.client import StrictPipeline
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework.response import Response
from rest_framework.views import  APIView
from django_redis import get_redis_connection
from MD_shop.libs.captcha.captcha import captcha
from celery_tasks.sms import task as sms_tasks

from users.models import User
from verifications import constants
from .serializers import ImageCodeCheckSerializer



class ImageCodeView(APIView):
    """
    图片验证码
    """
    def get(self,request,image_code_id):
        text, image = captcha.generate_captcha()
        
        
        redis_conn = get_redis_connection("verify_codes")
        redis_conn.setex("img_%s" % image_code_id, constants.IMAGE_CODE_REDIS_EXPIRES, text)
    
        return HttpResponse(image, content_type="images/jpg")


class SMSCodeView(GenericAPIView):
    serializer_class = ImageCodeCheckSerializer
    
    def get(self,request,mobile):
        serializer = self.get_serializer(data=request.query_params)
        serializer.is_valid(raise_exception=True)
        
        #生成随机密码
        sms_code = "%06d" % random.randint(0,999999)

        #保存短信验证码和发送记录
        redis_conn = get_redis_connection('verify_codes')
        pl = redis_conn.pipeline()
        pl.setex("sms_%s" % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex("send_flag_%s" % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()
        
        #发送短信
        sms_tasks.send_sms_code.delay(mobile,sms_code)
        
        print(sms_code)
        return Response({"message":"ok"})
        
        
class SMSCodeByTokenView(APIView):
    """根据access_token发送短信"""
    def get(self, request):
        # 获取并校验 access_token
        access_token = request.query_params.get('access_token')
        if not access_token:
            return Response({"message": "缺少access token"}, status=status.HTTP_400_BAD_REQUEST)

        # 从access_token中取出手机号
        mobile = User.check_send_sms_code_token(access_token)
        if mobile is None:
            return Response({"message": "无效的access token"}, status=status.HTTP_400_BAD_REQUEST)


        # 判断手机号发送的次数
        redis_conn = get_redis_connection('verify_codes')
        send_flag = redis_conn.get('send_flag_%s' % mobile)
        if send_flag:
            return Response({"message": "发送短信次数过于频"}, status=status.HTTP_429_TOO_MANY_REQUESTS)

        # 生成短信验证码
        # 发送短信验证码
        sms_code = '%06d' % random.randint(0, 999999)

        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, constants.SMS_CODE_REDIS_EXPIRES, sms_code)
        pl.setex('send_flag_%s' % mobile, constants.SEND_SMS_CODE_INTERVAL, 1)
        pl.execute()

        from celery_tasks.sms.task import send_sms_code
        send_sms_code.delay(mobile, sms_code)

        # 返回
        return Response({'message': 'OK'})
